using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Threading.Tasks;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using WebSMS.Core.ResponseEntity;

namespace WebSMS;

public class DepartmentService : ITerDepartment,ITransient
{
        private readonly IRepository<Department> _repo;
        private readonly UserDepartmentLinksService _departmentLinksService;
        private readonly IRepository<UserPo> _userRepository;
        private readonly IRepository<PostPo> _postRepository;
        private readonly IRepository<UserPostLinks> _userPostLinks;
    public DepartmentService(IRepository<Department> repository,
        UserDepartmentLinksService departmentLinksService,
        IRepository<UserPo> userRepository,
        IRepository<PostPo> postRepository,
        IRepository<UserPostLinks> userPostLinks)
    {
        _repo = repository;
        _departmentLinksService = departmentLinksService;
        _userRepository = userRepository;
        _postRepository = postRepository;
        _userPostLinks = userPostLinks;
    }

    public async Task<bool> AddDepartment(Department department)
    {
       await _repo.InsertNowAsync(department);
       return true;
    }

    public async Task<bool> UpdateDepartment(Department department)
    {
        await _repo.UpdateNowAsync(department);
        return true;
    }

    public async Task<bool> DeleteDepartment(Guid id)
    {
        // 检查该部门下属是否存在用户
       var status =  await _departmentLinksService.DeleteDepartment(id);
      //检查该部门是否还有子部门
       var queryable = _repo.Where(d => d.ParentId == id);
       if (!status || !(queryable.Any()))
       {
         await _repo.DeleteNowAsync(id);
         return true;
       }
       return false;
    }

    public List<DepartmentCollection> GetDepartment()
    {
        var firstDepartments = _repo.Where(d => d.ParentId == null);
        var otherDepartments = _repo.Where(d => d.ParentId != null);
        List<DepartmentCollection> trees = GetDepartmentTrees(firstDepartments, otherDepartments);
        return trees;
    }

    public  List<DepartmentCollection> GetDepartmentTrees(IQueryable<Department> firstDepartments,IQueryable<Department> otherDepartments)
    {
        List<DepartmentCollection> departmentCollections = new List<DepartmentCollection>();
        foreach (var item in firstDepartments)
        {
            departmentCollections.Add(new DepartmentCollection()
            {
                Id = item.Id,
                Name = item.Name,
                Description = item.Description,
            });
        }
        foreach (var item in otherDepartments)
        {
            foreach (var departmentCollection in departmentCollections)
            {
                if (departmentCollection.Id == item.ParentId)
                {
                    departmentCollection.ChildDepartments.Add(new DepartmentCollection(){
                        Id = item.Id, 
                        Name = item.Name, 
                        Description = item.Description,
                        ParentId = item.ParentId});
                }
            }
        }
        return departmentCollections;
    }
    
    public int GetDepartmentCount()
    {
        return _repo.Count();
    }


    public async Task<Object> GetDepartmentDetail(Guid id)
    {
        // 获取指定部门的所有岗位
        var posts = await _postRepository.AsQueryable()
            .Where(p => p.DepartmentId == id)
            .Select(p => new PostDto
            {
                PostId = p.Id.Value,
                PostName = p.Name,
                DepartmentId = p.DepartmentId.Value
            })
            .ToListAsync();

        // 获取所有与这些岗位关联的用户链接
        var postIds = posts.Select(p => p.PostId).ToList();
        var userPostLinks = await _userPostLinks.AsQueryable()
            .Where(upl => postIds.Contains(upl.PostId))
            .ToListAsync();

        // 获取所有相关的用户
        var userIds = userPostLinks.Select(upl => upl.UserId).Distinct().ToList();
        var users = await _userRepository.AsQueryable()
            .Where(u => userIds.Contains(u.Id))
            .Select(u => new UserDto
            {
                UserId = u.Id,
                Username = u.Username,
                Email = u.Email,
                Phone = u.Phone,
                IsActive = u.IsActive
            })
            .ToListAsync();

        // 组装最终结果
        var result = new DepartmentDetailsResponse
        {
            Posts = posts.Select(p => new PostDto
            {
                PostId = p.PostId,
                PostName = p.PostName,
                DepartmentId = p.DepartmentId,
                Users = userPostLinks
                    .Where(upl => upl.PostId == p.PostId)
                    .Join(users, upl => upl.UserId, u => u.UserId, (upl, u) => u)
                    .ToList()
            }).ToList()
        };

        return result;
    }
}